// import axios from 'axios';
import axios from 'axios/dist/axios';
import cache from '@/utils/cache';
import config from '@/config';
import message from '@/utils/message';
import secret from '@/utils/secret';

interface axiosConfigType {
    baseURL?:string,
    timeout:number
}

const clearCache = () => 
{
    cache.userData.remove();
    cache.token.remove();
    cache.backupId.remove();
    window.location.reload();
};
const isProduction = process.env.NODE_ENV === 'production',
    axiosConfig:axiosConfigType = {
        'baseURL':'',
        'timeout': 20000
    };

if (isProduction)
{
    axiosConfig.baseURL = import.meta.env.VITE_APP_API_URL;
}
const allowPath:string[] = ['/login', '/register', '/forget'];
const errorCode:string[] = ['XP000', 'XP001', 'XP002', 'XP003', 'XP025'];
const service = axios.create(axiosConfig);

service.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
service.defaults.headers.get['Content-Type'] = 'application/json;charset=utf-8';
service.defaults.headers.put['Content-Type'] = 'application/json;charset=utf-8';
service.defaults.headers.delete['Content-Type'] = 'application/json;charset=utf-8';

// 请求拦截器
service.interceptors.request.use(
    (req) =>
    {
        let date = new Date().getTime();
        if (req && req?.headers && req?.url)
        {
            req.headers['timeStamp'] = date;
            req.headers['signTimeStamp'] = secret.Encrypt(date.toString());
            
            let flag = allowPath.findIndex((item) => 
            { 
                if (req?.url)
                {
                    return req.url.indexOf(item) > -1;
                }
                return -1;
            });
            
            if (flag > -1) 
            {
                return req;
            }
            if (cache.token.get())
            {
                req.headers.token = 'xp ' + cache.token.get();
            }
            else
            {
                message.error('token不存在，请重新登录');
                // 清除本地用户缓存
                clearCache();
            }
        }
        return req;
    },
    (error) =>
    {
        Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) =>
    {
        const res = response.data;
        if (response.headers['content-type'] === 'image/png;')
        {
            return res;
        }
        if (!res.success)
        {
            if (errorCode.includes(res.errcode))
            {
                // 身份验证
                message.error(res.errcode + '-' + res.errmsg);
                setTimeout(() => 
                {
                    // 清除本地用户缓存
                    clearCache();
                }, 1000);
            }
            else 
            {
                // 其他错误处理
                message.error(res.errcode + '-' + res.errmsg);
                return Promise.reject(new Error(res.errcode + '-' + res.errmsg));
            }
        }
        return res;
    },
    (error) =>
    {
        if (error.message === 'timeout of 10000ms exceeded')
        {
            message.error('请求超时');
            return Promise.reject(error);
        }
        
        // 500 请求错误处理,打印后台报错详细信息
        if (error.response.status === 500) 
        {
            message.error(error.response.data.msg);
            return Promise.reject(error);
        }
        // 其他错误
        message.error(error.message);
        return Promise.reject(error);
    }
);

export default service;
